import { apiArea } from 'js/api'
import { storage } from 'util/storage'

export default {
  state: {
    areaList: []
  },
  getters: {
    areaList: state => state.areaList
  },
  actions: {
    fetchArea({ state, commit }, payload) {
      const area = storage.get('areaList')
      if (area) {
        commit('setAddressList', area)
      } else {
        apiArea().then(data => {
          const oArea = data.areaList || []
          const oNewArea = []
          oArea.forEach((area, areaIndex) => {
            oNewArea.push({
              v: area.id + '',
              n: area.areaName + '',
              c: []
            })
            area.childs.forEach((city, cityIndex) => {
              oNewArea[areaIndex].c.push({
                v: city.id + '',
                n: city.areaName + '',
                c: []
              })
              city.childs.forEach(prov => {
                oNewArea[areaIndex].c[cityIndex].c.push({
                  v: prov.id + '',
                  n: prov.areaName + ''
                })
              })
            })
          })
          storage.set('areaList', oNewArea)
          commit('setAddressList', oNewArea)
        })
      }
    }
  },
  mutations: {
    setAddressList(state, payload) {
      state.areaList = payload
    }
  }
}
